package com.tg.service.eventbus2.springconfig;

import com.google.common.collect.Lists;
import com.tg.service.base.createbean.B;
import com.tg.service.eventbus2.Component;
import com.tg.service.eventbus2.ComponentBus;
import com.tg.service.eventbus2.component.CheckGroupCp;
import com.tg.service.eventbus2.component.FirstLoginCp;
import com.tg.service.eventbus2.service.UserService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class ComponentFactoryBean implements FactoryBean<Component>, ApplicationContextAware, BeanNameAware {

    private ApplicationContext context;

    private String beanName;

    private static final Map<String, Function<ApplicationContext, Component>> BEAN_NAME_2_CP = new HashMap<>();

    static {
        BEAN_NAME_2_CP.put("FirstLoginCp", ctx -> {
            UserService userService = (UserService) ctx.getBean("loadUserService");
            return new FirstLoginCp(userService);
        });
        BEAN_NAME_2_CP.put("CheckGroupCp", (ctx) -> new CheckGroupCp());
    }

    @Override
    public Component getObject() throws Exception {
        Function<ApplicationContext, Component> function = BEAN_NAME_2_CP.get(this.beanName);
        return function.apply(this.context);
    }

    @Override
    public Class<?> getObjectType() {
        return Component.class;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
